package com.zijidelu.luframework.infrastructure.model.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zijidelu.luframework.base.model.BaseModel;
import com.zijidelu.luframework.base.model.PO;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @author ZIJIDELU
 * @datetime 2025/3/30 19:46
 */
public class PageQuery<D extends BaseModel> implements Serializable {
    @Serial
    private static final long serialVersionUID = -1328124698923739773L;

    private Long size = 10L;
    private Long current = 1L;
    private List<OrderItem> orders;
    private Boolean searchCount = true;
    private D data;

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public Long getCurrent() {
        return current;
    }

    public void setCurrent(Long current) {
        this.current = current;
    }

    public List<OrderItem> getOrders() {
        return orders;
    }

    public void setOrders(List<OrderItem> orders) {
        this.orders = orders;
    }

    public Boolean getSearchCount() {
        return searchCount;
    }

    public void setSearchCount(Boolean searchCount) {
        this.searchCount = searchCount;
    }

    public D getData() {
        return data;
    }

    public void setData(D data) {
        this.data = data;
    }

    /**
     * 转换为 MyBatis-Plus 的分页对象
     */
    public <P extends PO> IPage<P> toPage() {
        Page<P> page = new Page<>();

        // 默认页码 = 1
        page.setCurrent(Objects.requireNonNullElse(current, 1L));

        // 默认每页大小 = 10
        page.setSize(Objects.requireNonNullElse(size, 10L));

        if (Objects.nonNull(searchCount)) {
            page.setSearchCount(searchCount);
        }
        if (Objects.nonNull(orders) && !orders.isEmpty()) {
            page.setOrders(orders);
        }

        return page;
    }

    /**
     * 复制分页参数并替换数据对象
     */
    public <T extends BaseModel> PageQuery<T> copyWith(T data) {
        PageQuery<T> pageQuery = new PageQuery<>();
        pageQuery.setSize(size);
        pageQuery.setCurrent(current);
        pageQuery.setOrders(orders);
        pageQuery.setSearchCount(searchCount);
        pageQuery.setData(data);
        return pageQuery;
    }

}
